package com.qzd.springcloud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.qzd.springcloud.Service.DeptService;
import com.qzd.springclude.entity.Dept;

//@RestController返回json数据
@Controller
public class DeptController {
	@Autowired
	private DeptService deptservice;

	@Autowired
	private DiscoveryClient client;//服务发现
	
	@PostMapping(value="/dept/findbyid/{id}")
	@ResponseBody
    @HystrixCommand(fallbackMethod="errfindbyid")//服务熔断
	public Dept findByid(@PathVariable("id")Integer id) throws Exception{
		System.out.println(id);
	   Dept dept= deptservice.findbyid(id);
	   if(dept==null){
		   throw new Exception();
	   }
	   return dept;
	}
	//服务发现
	@GetMapping(value="dept/discovery")
	@ResponseBody
	public Object discovery(){
		List<String> list = client.getServices();
	    System.out.println("**********" + list);
	 
	    List<ServiceInstance> srvList = client.getInstances("microservicecloud-dept");
	    for (ServiceInstance element : srvList) {
	     System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
	         + element.getUri());
	    }
	    return this.client;
	}
	public  Dept errfindbyid(Integer id){
		//return new Dept().setDeptno(0).setDname("没有该id信息").setDb_source("no mysql");
		Dept dept=new Dept();
		dept.setDeptno(0).setDname("没有该id信息").setDb_source("nomysql");
		return dept;
	}

}
